﻿package game.fileloader {
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLLoaderDataFormat;
	import flash.events.ProgressEvent;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	
	public class FileLoader extends URLLoader {
		
		private var files:Array;
		private var current:int = -1;
		private var status:String = "init";
		
		public function FileLoader():void {
			files = new Array;
			
			this.dataFormat = URLLoaderDataFormat.BINARY;
			
			this.addEventListener(ProgressEvent.PROGRESS,	progressHandler);
			this.addEventListener(Event.COMPLETE,			completeHandler);
			this.addEventListener(IOErrorEvent.IO_ERROR,	errorHandler);
		}
		
		public function set (url:String, params:Object = null):void {
			files.push({params: params, url: url});
			nextLoad();
		}
		
		private function nextLoad():void {
			if (status!='loading' && current+1<files.length) {
				current++;
				status = 'loading';
				try { super.close(); } catch (e:Error) { }
				super.load( new URLRequest (files[current].url) );
			}
		}
		
		public override function close():void {
			if (status=='loading') {
				status = 'error';
				current++;
				super.close();
			}
		}
		
		private function completeHandler(event:Event):void {
			status = 'loaded';
			this.dispatchEvent( new FileLoaderEvent ( FileLoaderEvent.LOADED, files[current].params, this.data ) );
			nextLoad();
		}
		
		private function errorHandler(event:IOErrorEvent):void {
			status = 'error';
			this.dispatchEvent( new FileLoaderEvent ( FileLoaderEvent.ERROR, files[current].params, null ) );
			nextLoad();
		}
		
		private function progressHandler(event:ProgressEvent):void { 
			//event.bytesLoaded/event.bytesTotal;
		}
		
	}
	
}